package com.wsz.logistic.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsz.logistic.bean.District;
import com.wsz.logistic.bean.Warehouse;
import com.wsz.logistic.common.util.R;
import com.wsz.logistic.mapper.DistrictMapper;
import com.wsz.logistic.mapper.WarehouseMapper;
import com.wsz.logistic.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class WarehouseSericeImpl implements WarehouseService {
    @Autowired
    private DistrictMapper districtMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    public R getPage(int page, int limit, Warehouse warehouse) {
        PageHelper.startPage(page, limit);
        List<Warehouse> warehouses = warehouseMapper.getAll(warehouse);
        PageInfo<Warehouse> pageInfo = new PageInfo<Warehouse>(warehouses);
        return R.page(pageInfo.getTotal(), pageInfo.getList());
    }

    public void sync() {
        List<District> districts = districtMapper.getAll();
        List<Warehouse> warehouses = warehouseMapper.getAll();
        Set<String> namesSet = warehouses.stream()
                .map(Warehouse::getName)
                .collect(Collectors.toSet());
        for (District d : districts) {
            if (!namesSet.contains(d.getName())) {
                Warehouse newWarehouse = new Warehouse();
                newWarehouse.setName(d.getName());
                warehouseMapper.insertSelective(newWarehouse);
            }
        }
    }

    @Override
    public void saveOrUpdate(Warehouse warehouse) {
        if (warehouse.getWarehouseId() == null) {
            warehouseMapper.insertSelective(warehouse);
        } else {
            warehouseMapper.updateByPrimaryKeySelective(warehouse);
        }
    }

    @Override
    public void deleteById(int warehouseId) {
        warehouseMapper.deleteByPrimaryKey(warehouseId);
    }

    @Override
    public Warehouse getById(int warehouseId) {
        return warehouseMapper.selectByPrimaryKey(warehouseId);
    }
}
